<template>
	<page-meta :page-style="themeColor"></page-meta>
	<view class="container">
		<view class="content">
			<view class="wx-code"><image :src="$util.img(path)" /></view>
			<view class="get-coupon">
				<text class="coupon-name">{{ info.coupon_name }}</text>
				<view class="color-base-text coupon-price" v-if="info.type == 'reward'">￥{{ info.money }}</view>
				<view class="color-base-text coupon-price" v-else-if="info.type == 'discount'">{{ info.discount }}折</view>
				<text v-if="info.at_least > 0" class="color-tip">满{{ info.at_least }}元使用</text>
				<text v-else class="color-tip">无门槛优惠券</text>
				<view v-if="info.validity_type == 0" class="color-tip">有效期至 {{ $util.timeStampTurnTime(info.end_time) }}</view>
				<view v-else-if="info.validity_type == 1" class="color-tip">领取之日起{{ info.fixed_term }}天内有效</view>
				<view v-else class="color-tip">长期有效</view>

				<view class="get-span" @click="receiveGoodsCoupon(info.coupon_type_id)">
					<button type="primary" v-if="isCanReceive">{{ button }}</button>
					<button type="primary" disabled v-if="!isCanReceive">{{ button }}</button>
				</view>

				<view class="color-tip font-size-goods-tag tips">注:扫描二维码或点击右上角进行分享</view>
			</view>
		</view>
		<loading-cover ref="loadingCover"></loading-cover>
		<ns-login ref="login"></ns-login>
	</view>
</template>

<script>
export default {
	data() {
		return {
			info: {},
			couponTypeId: 0,
			path: '',
			button: '领取',
			uid: 0,
			couponBtnSwitch: false, //获取优惠券防止重复提交
			memberId: 0,
			receivedNum: 0
		};
	},
	onLoad(data) {
		setTimeout( () => {
			if (this.addonIsExist && !this.addonIsExist.coupon) {
				this.$util.showToast({
					title: '商家未开启优惠券',
					mask: true,
					duration: 2000
				});
				setTimeout(() => {
					this.$util.redirectTo('/pages/index/index');
				}, 2000);
				return;
			}
		}, 1000);
		
		if (data.source_member) uni.setStorageSync('source_member', data.source_member);

		if (data.coupon_type_id) this.couponTypeId = data.coupon_type_id;

		// 小程序扫码进入
		if (data.scene) {
			var sceneParams = decodeURIComponent(data.scene);
			sceneParams = sceneParams.split('&');
			if (sceneParams.length) {
				sceneParams.forEach(item => {
					if (item.indexOf('coupon_type_id') != -1) this.couponTypeId = item.split('-')[1];
					if (item.indexOf('m') != -1) {
						this.source_member = item.split('-')[1];
						uni.setStorageSync('source_member', data.source_member);
					}
				});
			}
		}
	},
	onShow() {
		this.getCoupon();
		this.receivedNum = 0;
		if (uni.getStorageSync('token')) {
			this.$util.getMemberId().then(resolve => {
				this.memberId = resolve;
				if (this.info.coupon_type_id) this.setPublicShare();
			});
			this.getReceivedNum();
		}
		//记录分享关系
		if (uni.getStorageSync('token') && uni.getStorageSync('source_member')) {
			this.$util.onSourceMember(uni.getStorageSync('source_member'));
		}
	},
	onHide() {
		this.couponBtnSwitch = false;
	},
	methods: {
		getCoupon() {
			this.$api.sendRequest({
				url: '/coupon/api/coupon/typeinfo',
				data: {
					coupon_type_id: this.couponTypeId
				},
				success: res => {
					let data = res.data;
					if (data) {
						this.info = data;
						this.path = data.qrcode;
						if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
						this.buttonRefresh();
						this.setPublicShare();
					} else {
						this.$util.showToast({
							title: res.message
						});
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							});
						}, 1000);
					}
				},
				fail: res => {
					if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
				}
			});
		},
		receiveGoodsCoupon(couponTypeId) {
			if (!uni.getStorageSync('token')) {
				this.$refs.login.open('/pages_tool/goods/coupon_receive?coupon_type_id=' + this.couponTypeId);
				return;
			}

			if (!this.isCanReceive) return;

			if (this.couponBtnSwitch) return;
			this.couponBtnSwitch = true;

			this.$api.sendRequest({
				url: '/coupon/api/coupon/receive',
				data: {
					coupon_type_id: couponTypeId,
					get_type: 2 //获取方式:1订单2.直接领取3.活动领取
				},
				success: res => {
					var data = res.data;
					let msg = res.message;
					if (res.code == 0) {
						msg = '领取成功';
						this.receivedNum += 1;
						this.buttonRefresh();
					}
					this.$util.showToast({
						title: msg
					});
					this.couponBtnSwitch = false;
				},
				fail: res => {
					this.couponBtnSwitch = false;
				}
			});
		},
		getReceivedNum() {
			this.$api.sendRequest({
				url: '/coupon/api/coupon/receivedNum',
				data: {
					coupon_type_id: this.couponTypeId
				},
				success: res => {
					if (res.code >= 0) {
						this.receivedNum = res.data;
						this.buttonRefresh();
					}
				}
			});
		},
		buttonRefresh() {
			this.button = '领取';
			if (this.info.count == this.info.lead_count) {
				this.button = '来迟了该优惠券已被领取完了';
			} else if (this.info.max_fetch == 0 || this.receivedNum == 0) {
				this.button = '领取';
			} else if (this.info.max_fetch > this.receivedNum) {
				this.button = '领取';
			} else {
				this.button = '该优惠券领取已达到上限';
			}
		},
		/**
		 * 设置公众号分享
		 */
		setPublicShare(){
			let shareUrl = this.$config.h5Domain + '/pages_tool/goods/coupon_receive?coupon_type_id=' + this.couponTypeId;
			if (this.memberId) shareUrl += '&source_member=' + this.memberId;
		
			var title = '恭喜您获得一张' + this.info.money + '元的优惠券';
			if (this.info.range_type == 1) {
				var desc = `满${this.info.at_least}全场可用`;
			} else {
				var desc = `满${this.info.at_least}部分商品可用`;
			}
			this.$util.setPublicShare({
				title: title, 
				desc: desc,
				link: shareUrl,
				imgUrl: this.$store.state.siteInfo ? this.$store.state.siteInfo.logo_square : ''
			})
		}
	},
	computed: {
		isCanReceive: {
			get() {
				if (this.info.count == this.info.lead_count) {
					return false;
				} else if (this.info.max_fetch == 0 || this.receivedNum == 0) {
					return true;
				} else if (this.info.max_fetch > this.receivedNum) {
					return true;
				} else {
					return false;
				}
			}
		}
	},
	/**
	 * 自定义分享内容
	 * @param {Object} res
	 */
	onShareAppMessage(res) {
		var title = '恭喜您获得一张' + this.info.money + '元的优惠券';
		if (this.info.range_type == 1) {
			title += `,满${this.info.at_least}全场可用`;
		} else {
			title += `,满${this.info.at_least}部分商品可用`;
		}
		var path = '/pages_tool/goods/coupon_receive?coupon_type_id=' + this.couponTypeId;
		if (this.memberId) path += '&source_member=' + this.memberId;
		return {
			title: title,
			path: path,
			success: res => {},
			fail: res => {}
		};
	}
};
</script>

<style lang="scss">
page {
	height: 100%;
}

.container {
	background: #fff;
	padding: 0;
	height: 100vh;
}

.content {
	background: url()
		no-repeat;
	background-size: 100% auto;
	height: 100%;
}

.wx-code {
	position: relative;
	margin: 0 auto;
	top: 34%;
	width: 320rpx;
	height: 320rpx;
	text-align: center;
	padding: 14rpx;
	box-shadow: 0 0 40rpx -2rpx;
}

.wx-code image {
	width: 320rpx;
	height: 320rpx;
}

.get-coupon {
	position: relative;
	margin: 0 auto;
	width: 560rpx;
	top: 37%;
	text-align: center;
	height: 366rpx;

	.coupon-name {
		font-size: $font-size-toolbar;
	}
}

.get-span {
	text-align: center;
	display: block;
	border-radius: 6rpx;
	margin-top: 29px;
	margin-bottom: 20rpx;
	height: 80rpx;
	line-height: 80rpx;
	color: #fff;
}

.get-coupon .tips {
	height: 40rpx;
}

.coupon-price {
	font-size: 52rpx;
	height: 76rpx;
}

button {
	box-shadow: 1px 2px 5px rgba(0, 0, 0, 0.3);
}
</style>
